// pages/settings/settings.ts
import { AppSettings, LessonTime } from '@/typings';
import { showToast, showConfirmDialog, formatDateToYYYYMMDD } from '../../../../../../utils/base';

const DEFAULT_SETTINGS: AppSettings = {
  totalWeeks: 18,
  startDate: formatDateToYYYYMMDD(new Date()),
  lessonTimes: [
    { index: 1, startTime: '08:00', endTime: '08:45' },
    { index: 2, startTime: '08:50', endTime: '09:35' },
    { index: 3, startTime: '09:50', endTime: '10:35' },
    { index: 4, startTime: '10:40', endTime: '11:25' },
    { index: 5, startTime: '11:30', endTime: '12:15' },
    { index: 6, startTime: '14:00', endTime: '14:45' },
    { index: 7, startTime: '14:50', endTime: '15:35' },
    { index: 8, startTime: '15:50', endTime: '16:35' },
    { index: 9, startTime: '16:40', endTime: '17:25' },
    { index: 10, startTime: '18:30', endTime: '19:15' },
    { index: 11, startTime: '19:20', endTime: '20:05' },
    { index: 12, startTime: '20:10', endTime: '20:55' },
  ].sort((a,b) => a.index - b.index),
};

Page({
  data: {
    appSettings: DEFAULT_SETTINGS,
    showLessonTimeEditor: false,
    lessonEditorData: { index: 0, startTime: '00:00', endTime: '00:00' } as LessonTime,
    editLessonIndex: null as number | null,
  },

  onLoad() {
    this.loadSettings();
  },
  
  onUnload() {
    const eventChannel = this.getOpenerEventChannel();
    if (eventChannel) {
      eventChannel.emit('settingsUpdated');
    }
  },

  loadSettings() {
    try {
      const storedSettingsStr = wx.getStorageSync('appSettings');
      if (storedSettingsStr) {
        const settings: AppSettings = JSON.parse(storedSettingsStr);
        settings.lessonTimes.sort((a, b) => a.index - b.index);
        this.setData({
          appSettings: settings,
        });
      } else {
        this.setData({ appSettings: DEFAULT_SETTINGS });
        this.saveSettingsToStorage(false); // 首次不提示
      }
    } catch (e) {
      console.error('加载设置失败', e);
      showToast('加载设置失败，使用默认设置');
      this.setData({ appSettings: DEFAULT_SETTINGS });
    }
  },

  saveSettingsToStorage(showSuccessToast: boolean = true) {
    try {
      wx.setStorageSync('appSettings', JSON.stringify(this.data.appSettings));
      if (showSuccessToast) {
        showToast('设置已保存');
      }
    } catch (e) {
      console.error('保存设置失败', e);
      showToast('保存设置失败');
    }
  },

  onSaveSettings() {
    const { appSettings } = this.data;
    if (!appSettings.totalWeeks || appSettings.totalWeeks <= 0) {
      showToast('请输入有效的学期总周数');
      return;
    }
    if (!appSettings.startDate) {
      showToast('请选择开学日期');
      return;
    }
    if (appSettings.lessonTimes.length === 0) {
      showToast('请至少设置一个节次时间段');
      return;
    }
    this.saveSettingsToStorage();
  },

  onFieldChange(e: WechatMiniprogram.CustomEvent) {
    const { field } = e.currentTarget.dataset;
    let value: any = e.detail;
    if (field === 'totalWeeks') {
      value = parseInt(value, 10);
      if (isNaN(value)) value = 0;
    }
    this.setData({
      [`appSettings.${field}`]: value,
    });
  },

  onStartDateChange(e: WechatMiniprogram.PickerChange) {
    this.setData({
      'appSettings.startDate': e.detail.value as string,
    });
  },

  onAddLessonTime() {
    const nextIndex = this.data.appSettings.lessonTimes.length > 0
      ? Math.max(...this.data.appSettings.lessonTimes.map(lt => lt.index)) + 1
      : 1;
    this.setData({
      lessonEditorData: { index: nextIndex, startTime: '09:00', endTime: '10:00' },
      editLessonIndex: null,
      showLessonTimeEditor: true,
    });
  },

  onEditLessonTime(e: WechatMiniprogram.CustomEvent) {
    const { index } = e.currentTarget.dataset;
    const lessonTime = this.data.appSettings.lessonTimes[index];
    this.setData({
      lessonEditorData: { ...lessonTime },
      editLessonIndex: index,
      showLessonTimeEditor: true,
    });
  },

  async onDeleteLessonTime(e: WechatMiniprogram.CustomEvent) {
    const { index } = e.currentTarget.dataset;
    const { lessonTimes } = this.data.appSettings;
    const lesson = lessonTimes[index];
    const confirm = await showConfirmDialog('删除确认', `确定删除第 ${lesson.index} 节课吗？`);
    if (confirm) {
      const newLessonTimes = lessonTimes.filter((_, i) => i !== index);
      this.setData({
        'appSettings.lessonTimes': newLessonTimes,
      });
      showToast('删除成功');
    }
  },

  onLessonEditorFieldChange(e: WechatMiniprogram.CustomEvent) {
    const { field } = e.currentTarget.dataset;
    let value: any = e.detail;
    if (field === 'index') {
      value = parseInt(value, 10);
      if (isNaN(value)) value = 0;
    }
    this.setData({
      [`lessonEditorData.${field}`]: value,
    });
  },

  onLessonTimeChange(e: WechatMiniprogram.PickerChange) {
    const { field } = e.currentTarget.dataset;
    this.setData({
      [`lessonEditorData.${field}`]: e.detail.value as string,
    });
  },

  onSaveLessonTime() {
    const { lessonEditorData, appSettings, editLessonIndex } = this.data;
    if (!lessonEditorData.index || lessonEditorData.index <= 0) {
      showToast('请输入有效的节次序号');
      return;
    }
    if (!lessonEditorData.startTime || !lessonEditorData.endTime) {
      showToast('请选择节次时间');
      return;
    }
    if (lessonEditorData.startTime >= lessonEditorData.endTime) {
      showToast('开始时间必须早于结束时间');
      return;
    }

    let newLessonTimes = [...appSettings.lessonTimes];

    const isIndexDuplicated = newLessonTimes.some((item, idx) =>
      item.index === lessonEditorData.index && idx !== editLessonIndex
    );
    if (isIndexDuplicated) {
      showToast(`节次序号 ${lessonEditorData.index} 已存在`);
      return;
    }

    if (editLessonIndex !== null) {
      newLessonTimes[editLessonIndex] = { ...lessonEditorData };
    } else {
      newLessonTimes.push({ ...lessonEditorData });
    }

    newLessonTimes.sort((a, b) => a.index - b.index);

    this.setData({
      'appSettings.lessonTimes': newLessonTimes,
      showLessonTimeEditor: false,
    });
    showToast('节次时间已保存');
  },

  onCloseLessonTimeEditor() {
    this.setData({ showLessonTimeEditor: false });
  },
});
